package com.formiaomiao.demain.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.PhotoAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.helper.RecyclerItemClickListener;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.util.UUIDS;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ComplaintFriendActivity extends BaseActivity {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_class_submit)
    TextView tvClassSubmit;
    @BindView(R.id.et_complaint_content)
    EditText etComplaintContent;
    @BindView(R.id.rl_complaint_photo)
    RecyclerView rlComplaintPhoto;

    LoadingDialog dialog;

    private PhotoAdapter photoAdapter;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    List<String> photos = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaint_friend);
        ButterKnife.bind(this);
        ViewInit();
    }

    private void ViewInit() {
        tvClassName.setText("投诉内容");
        tvClassSubmit.setText("投诉");
        dialog = new LoadingDialog(this);
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        rlComplaintPhoto.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        rlComplaintPhoto.setAdapter(photoAdapter);
        rlComplaintPhoto.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(PhotoAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(selectedPhotos)
                                    .start(ComplaintFriendActivity.this);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(ComplaintFriendActivity.this);
                        }
                    }
                }));
    }

    /**
     * 压缩多图
     *
     * @param pathList 传入的为图片原始路径
     */
    private void compressMore(final List<String> pathList) {
        final LinkedList<Runnable> taskList = new LinkedList<>();
        final ArrayList<File> newList = new ArrayList<>();//压缩后的图片路径
        final Handler handler = new Handler();
        class Task implements Runnable {
            String path;

            Task(String path) {
                this.path = path;
            }

            @Override
            public void run() {
                Luban.with(ComplaintFriendActivity.this)
                        .load(new File(path))                     //传人要压缩的图片
                        .putGear(3)      //设定压缩档次，默认三挡
                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                                dialog.show();
                            }

                            @Override
                            public void onSuccess(File file) {
                                newList.add(file);
                                if (!taskList.isEmpty()) {
                                    Runnable runnable = taskList.pop();
                                    handler.post(runnable);
                                } else {
                                    //完成之后的个人操作
                                    DataSubmitDataInit(newList);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();    //启动压缩
            }
        }
        //循环遍历原始路径 添加至linklist中
        for (String path : pathList) {
            taskList.add(new Task(path));
        }
        handler.post(taskList.pop());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
            photos.clear();
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {
                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 举报
     *
     * @param list
     */
    public void DataSubmitDataInit(List<File> list) {
        HttpParams params = new HttpParams();
        params.put("toid", StaticValues.userid);
        params.put("userid", getIntent().getIntExtra("id", 0));
        params.put("complaint", etComplaintContent.getText().toString().trim());
        params.put("mac", UUIDS.getUUID());
        if (list != null) {
            params.putFileParams("complaintimg", list);
        } else {
            params.putFileParams("complaintimg", null);
        }
        OkGo.<String>post(BaseUrl.INSERTCOMPLAINT)
                .headers("Authorization", PreferenceUtils.getString(ComplaintFriendActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(ComplaintFriendActivity.this, "投诉成功");
                    finish();
                } else {
                    ToastUtils.show(ComplaintFriendActivity.this, "投诉失败");
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dialog.dismiss();
                ToastUtils.show(ComplaintFriendActivity.this, "投诉失败");
            }
        });
    }

    @OnClick({R.id.iv_class_back, R.id.tv_class_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.tv_class_submit:
                if (etComplaintContent.getText().toString().isEmpty()) {
                    ToastUtils.show(this, "请输入投诉内容");
                } else {
                    if(photos.size()>0){
                        compressMore(photos);
                    }else{
                        dialog.show();
                        DataSubmitDataInit(null);
                    }
                }
                break;
        }
    }
}
